package algorithms;

import test.*;

/*
 * insert sort;
 * sort an int array in ascend order;
 */

public class insertSort {

	/**
	 * @param args
	 */
	public int[] a;
	
	public insertSort(int[] input) {
		a = input;
	}
	
	public int[] sort() { //sort function;
		int len = a.length;
		for(int j=1; j<len; j++) {
			int right = j;
			int left = j-1;
				
			while((left>=0) && (a[left] > a[right])) {
				int temp = a[left];
				a[left] = a[right];
				a[right] = temp;
				
				right--;
				left--;
			}
		}
		
		return a;
	}
	
	public void print(int[] input) {
		System.out.print(input[0]);
		for(int i=1; i<input.length; i++) {
			System.out.print(", ");
			System.out.print(input[i]);
		}
		
		System.out.println();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int size = 10;
		inputData ind = new inputData(size);
		ind.randomIntVector();
		ind.print();
		System.out.println(" ");
		
		insertSort is = new insertSort(ind.data);
		int b[] = is.sort();
		System.out.println("insert sort result: ");
		is.print(b);
		
		for(int i=0; i<size-1; i++) { // check ascend
			if(b[i]>b[i+1]) {
				System.out.println("bugs, index="+i+" & "+(i+1));
				return ;
			}
		}
		
		System.out.println("\ntest pass.");
	}
}
